package com.xhy.documents_collection.service.impl;

import com.xhy.documents_collection.entity.PO.log.LoginLog;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.holder.ExtraHolder;
import com.xhy.documents_collection.service.LoginServer;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.thread_pool.LogThreadPool;
import com.xhy.documents_collection.utils.JwtUtils;
import com.xhy.documents_collection.utils.R;
import com.xhy.documents_collection.utils.ServletUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Author: Xhy
 * CreateTime: 2022-11-14 16:59
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginServer {

    @Resource
    private UserService userService;

    @Override
    public R login(String username, String password) {

        User user = null;
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        boolean state = true;
        LoginLog loginLog = new LoginLog();

        String ip = ExtraHolder.get();
        loginLog.setIp(ip);
        loginLog.setBrowser(userAgent.getBrowser().toString());
        loginLog.setOperatingSystem(userAgent.getOperatingSystem().toString());
        loginLog.setUserName(username);
        if (username.contains("@")){
            // 邮箱登录
            user = userService.getUserByEmail(username);
        }else {
            // 学号登录
            user = userService.getUserByStudentNumber(username);
        }
        if (user == null){
            loginLog.setState(false);
            loginLog.setContent("账号不存在");
            LogThreadPool.addLoginLog(loginLog);
            return R.error().message("账号不存在");
        }
        if (!user.getPassword().equals(password)){
            loginLog.setState(false);
            loginLog.setContent("密码不一致");
            LogThreadPool.addLoginLog(loginLog);
            return R.error().message("密码不一致");
        }
        loginLog.setState(true);
        loginLog.setContent("登录成功");
        loginLog.setUserId(user.getId());
        LogThreadPool.addLoginLog(loginLog);
        // 保存至jwt
        String token = JwtUtils.getJwtToken(user.getId(), user.getName());
        return R.ok().message("登录成功").data("token",token).data("name",user.getName());
    }


}
